package com.guomei.service.curse.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.DistributionApply;
import com.guomei.bean.curse.GetByStatusDTO;
import com.guomei.mapper.curse.DistributionApplyMapper;
import com.guomei.service.curse.CourseService;
import com.guomei.service.curse.DistributionApplyService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 分销申请服务实现类
 */
@Service
@Slf4j
@Transactional
public class DistributionApplyServiceImpl implements DistributionApplyService {
    @Resource
    private DistributionApplyMapper distributionApplyMapper;

    @Resource
    private CourseService courseService;

    @Override
    public DistributionApply getById(Long id) {
        if (id == null) {
            return null;
        }
        return distributionApplyMapper.selectById(id);
    }

    @Override
    public DistributionApply getByCourseIdAndDistributorId(Long courseId, Long distributorId) {
        if (courseId == null || distributorId == null) {
            return null;
        }
        return distributionApplyMapper.selectByCourseIdAndDistributorId(courseId, distributorId);
    }

    @Override
    public List<DistributionApply> getByUserId(Long userId, Short status) {
        if (userId == null) {
            return null;
        }
        return distributionApplyMapper.selectByUserId(userId, status);
    }

    @Override
    public List<DistributionApply> getByCourseId(Long courseId, Short status) {
        if (courseId == null) {
            return null;
        }
        return distributionApplyMapper.selectByCourseId(courseId, status);
    }

    @Override
    public List<DistributionApply> getByTeacherId(Long teacherId, Short status) {
        if (teacherId == null) {
            return null;
        }
        return distributionApplyMapper.selectByTeacherId(teacherId, status);
    }

    @Override
    public Result<?> getByStatus(GetByStatusDTO getByStatusDTO) {
        PageHelper.startPage(getByStatusDTO.getPageNum(), getByStatusDTO.getPageSize());
        List<DistributionApply> distributionApplies = distributionApplyMapper.selectByStatus(getByStatusDTO.getStatus());
        // 封装分页结果到PageData
        PageData<DistributionApply> pageData = new PageData<>();
        PageInfo<DistributionApply> pageInfo = new PageInfo<>(distributionApplies);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(getByStatusDTO.getPageNum());
        pageData.setPageSize(getByStatusDTO.getPageSize());
        return Result.success(pageData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> submitApply(DistributionApply distributionApply) {

        // 验证分销比例是否合理(0-100之间)
        if (distributionApply.getDistributionRatio().compareTo(BigDecimal.ZERO) <= 0
                || distributionApply.getDistributionRatio().compareTo(new BigDecimal("100")) > 0) {
            return Result.fail("分销比例输入错误");
        }

        // 检查课程是否存在
        Course course = courseService.getById(distributionApply.getCourseId());
        if (course == null) {
            return Result.fail("课程不存在");
        }

        // 检查是否已申请过该课程的分销
        DistributionApply existApply = getByCourseIdAndDistributorId(
                distributionApply.getCourseId(), distributionApply.getDistributorId());
        if (existApply != null && !existApply.getUserId().equals(distributionApply.getUserId())) {
            return Result.fail("已申请过该课程和该用户的分销");
        }

        // 设置默认值
        LocalDateTime now = LocalDateTime.now();
        distributionApply.setStatus((short) 0); // 申请中
        distributionApply.setApplyTime(now);
        distributionApply.setCreatedTime(now);
        distributionApply.setUpdatedTime(now);
        int insert = distributionApplyMapper.insert(distributionApply);
        if (insert > 0){
            return Result.success("申请成功");
        }else {
            return Result.fail("申请失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> reviewApply(Long id, Short status, String reviewRemark) {
        // 参数验证
        if (id == null || status == null || (status != 1 && status != 2)) {
            return Result.fail("参数错误");
        }

        // 检查申请是否存在且状态为申请中
        DistributionApply apply = getById(id);
        if (apply == null || apply.getStatus() != 0) {
            return Result.fail("申请不存在或状态错误");
        }

        // 更新审核状态
        LocalDateTime now = LocalDateTime.now();
        int i = distributionApplyMapper.updateStatus(id, status, now, reviewRemark);

        if (i > 0){
            return Result.success("审核成功");
        }else {
            return Result.fail("审核失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(DistributionApply distributionApply) {
        if (distributionApply == null || distributionApply.getId() == null) {
            return false;
        }

        // 检查申请是否存在
        DistributionApply existApply = getById(distributionApply.getId());
        if (existApply == null) {
            return false;
        }

        // 已审核的申请不允许修改
        if (existApply.getStatus() != 0) {
            return false;
        }

        distributionApply.setUpdatedTime(LocalDateTime.now());
        return distributionApplyMapper.updateById(distributionApply) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        if (id == null) {
            return false;
        }

        // 检查申请是否存在
        DistributionApply apply = getById(id);
        if (apply == null) {
            return false;
        }

        // 只有申请中的记录可以删除
        if (apply.getStatus() != 0) {
            return false;
        }

        return distributionApplyMapper.deleteById(id) > 0;
    }
}
